import type Ts from 'typescript';
import { defineRule } from '@tsslint/config';
import type { Rule, RuleContext } from '@tsslint/config';
import { isEnumMember } from 'typescript';

const Warning_Title = 'prefer satisfies';

const Fix_Title = 'use `satisfies` replace `as`';

function enumSatisfies(): Rule {
  return defineRule(
    ({
      typescript: ts,
      sourceFile,
      reportWarning,
      languageService: ls,
    }: RuleContext) => {
      ts.forEachChild(sourceFile, function cb(node: Ts.Node) {
        if (
          ts.isAsExpression(node) /* xx as yy */
          // && ts.isEnumMember(node.getChildren()[2].getChildren()[0].getChildAt(2)) /* fail, cuz enumMember should in `EnumDeclaration`*/
        ) {
          reportWarning(
            `${Warning_Title} '${node.getText()} -- ${node.getChildren()[2]?.getChildren()[0]?.getChildAt(2)}'`,
            node.getStart(sourceFile),
            node.getEnd(),
          ).withFix(Fix_Title, () => [
            {
              fileName: sourceFile.fileName,
              textChanges: [
                {
                  newText: `/* #__DELETE__ ${node.getText()}:*/`,
                  span: {
                    start: node.getStart(sourceFile),
                    length: node.getWidth(sourceFile),
                  },
                },
              ],
            },
          ]);
        }
        ts.forEachChild(node, cb);
      });
    },
  );
}
export default enumSatisfies;
